package tr.edu.metu.is.mega.client;

import java.util.ArrayList;
import java.util.List;

import tr.edu.metu.is.mega.client.core.AsyncCallbackAdapter;
import tr.edu.metu.is.mega.client.core.AuthUtils;
import tr.edu.metu.is.mega.client.core.MainWindow;
import tr.edu.metu.is.mega.client.core.MegaUtil;
import tr.edu.metu.is.mega.client.core.QueryCallback;
import tr.edu.metu.is.mega.client.service.GwtUserCoursesViewService;
import tr.edu.metu.is.mega.common.dto.UserCoursesViewDTO;
import tr.edu.metu.is.mega.common.dto.UserDTO;
import tr.edu.metu.is.mega.common.dto.UserRole;

import com.extjs.gxt.ui.client.Style.LayoutRegion;
import com.extjs.gxt.ui.client.data.BeanModel;
import com.extjs.gxt.ui.client.data.BeanModelFactory;
import com.extjs.gxt.ui.client.data.BeanModelLookup;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.custom.Portal;
import com.extjs.gxt.ui.client.widget.custom.Portlet;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.layout.BorderLayout;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;
import com.extjs.gxt.ui.client.widget.layout.FillLayout;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.History;

/**
 * Panel to display a user's dashboard.
 */
public class UserDashboardWindow extends MainWindow {

    private Portlet portletTask;

    private Grid<BeanModel> grid;

    private Portal portal;

    /**
     * Default constructor.
     */
    public UserDashboardWindow() {
        super("UserDashboardWindow", null);
        setHeading("Dashboard");
        setLayout(new BorderLayout());
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void onRender(Element parent, int pos) {
        super.onRender(parent, pos);
        initialize();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void afterRender() {
        super.afterRender();
        GwtUserCoursesViewService.Util.getInstance().getCourses(new AsyncCallbackAdapter<List<UserCoursesViewDTO>>() {

            @Override
            public void onSuccess(List<UserCoursesViewDTO> result) {
                grid.getStore().removeAll();
                BeanModelFactory factory = BeanModelLookup.get().getFactory(UserCoursesViewDTO.class);
                for (UserCoursesViewDTO activity : result) {
                    grid.getStore().add(factory.createModel(activity));
                }
            }
        });
    }

    /**
     * Initializes this.
     */
    private void initialize() {
        portal = new Portal(1);
        portal.setBorders(true);
        portal.setStyleAttribute("backgroundColor", "white");
        portal.setColumnWidth(0, 1);
        // portal.setColumnWidth(1, 1 / 2);
        getTaskPortlet();
        // portal.add(getPostitPortlet(), 1);
        BorderLayoutData layoutData = new BorderLayoutData(LayoutRegion.CENTER);
        this.add(portal, layoutData);
    }

    /**
     * Initiates task portlet.
     */
    private void getTaskPortlet() {
        AuthUtils.getInstance().getCurrentUser(new QueryCallback<UserDTO>() {

            @Override
            public void onQueryResult(UserDTO result) {
                portletTask = new Portlet();
                portletTask.setLayout(new FillLayout());
                portletTask.setWidth(getWidth());
                portletTask.setHeading("Courses");
                portletTask.setCollapsible(true);
                portletTask.setAnimCollapse(true);
                portletTask.add(getGrid(result));
                portletTask.setHeight(250);
                portal.add(portletTask, 0);
            }
        });
    }

    /**
     * Returns activity grid.
     * 
     * @return grid
     */
    public Grid<BeanModel> getGrid(final UserDTO user) {
        if (grid == null) {

            ListStore<BeanModel> store = new ListStore<BeanModel>();

            List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
            columns.add(new ColumnConfig(UserCoursesViewDTO.FIELD_CODE, "Course Code", 100));
            columns.add(new ColumnConfig(UserCoursesViewDTO.FIELD_NAME, "Course Name", 100));
            columns.add(new ColumnConfig(UserCoursesViewDTO.FIELD_SEMESTER, "Course Semester", 100));
            if (user.getRole() == UserRole.ADMIN) {
                columns.add(new ColumnConfig(UserCoursesViewDTO.FIELD_USER, "Instructor", 100));
            }
            ColumnModel cm = new ColumnModel(columns);

            grid = new Grid<BeanModel>(store, cm);
            grid.addListener(Events.CellDoubleClick, new Listener<BaseEvent>() {

                @Override
                public void handleEvent(BaseEvent be) {
                    UserCoursesViewDTO dto = grid.getSelectionModel().getSelectedItem().getBean();
                    if (user.getRole() == UserRole.STUDENT) {
                        History.newItem("StudentCourseWindow:" + dto.getCourseid());
                    } else {
                        History.newItem("CourseInformationWindow:" + dto.getCourseid());
                    }
                }
            });

            MegaUtil.decoradeGridViewWithAutoHeight(grid, true);

        }
        return grid;
    }
}
